package cn.li.security.sms;


import cn.li.security.json.filter.UsernamePasswordJSONAuthenticationFilter;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class SmsAuthenticationJSONFilter extends SmsAuthenticationFormFilter {

    private ObjectMapper objectMapper;
    public SmsAuthenticationJSONFilter(String pattern, ObjectMapper objectMapper) {
        super();
        this.objectMapper = objectMapper;
        RequestMatcher urlMatcher = new AntPathRequestMatcher(pattern, "POST");
        this.setRequiresAuthenticationRequestMatcher(
                new AndRequestMatcher( urlMatcher,   UsernamePasswordJSONAuthenticationFilter.APPLICATION_JSON_MATCHER)
        );
    }


    //缓存一下解析出来的body
    private Map<String,String> requestBody = new HashMap<>();
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        try {
            requestBody = objectMapper.readValue(request.getInputStream(),new TypeReference<Map<String,String>>(){});
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.attemptAuthentication(request,response);
    }

    protected String obtainParameter(HttpServletRequest request , String paramName) {
        return requestBody.get(paramName);
    }

}